package cn.geminis.crypto.ocsp;

import cn.geminis.crypto.core.x509.X509Certificate;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.ocsp.CertificateID;
import org.bouncycastle.cert.ocsp.OCSPReqBuilder;
import org.bouncycastle.operator.DigestCalculator;
import org.bouncycastle.operator.bc.BcDigestCalculatorProvider;

import java.math.BigInteger;

public class OcspRequest {

    private X509CertificateHolder issuerHolder;
    private DigestCalculator digest;

    public OcspRequest(X509Certificate issuer) {
        try {
            issuerHolder = new X509CertificateHolder(issuer.getEncode());
            BcDigestCalculatorProvider digestProvider = new BcDigestCalculatorProvider();
            digest = digestProvider.get(CertificateID.HASH_SHA1);
        } catch (Exception e) {
            throw new RuntimeException("准备请求CertID错误", e);
        }
    }

    public byte[] generate(BigInteger serialNumber) {

        OCSPReqBuilder builder = new OCSPReqBuilder();
        try {
            CertificateID certId = new CertificateID(digest, issuerHolder, serialNumber);
            builder.addRequest(certId);
            return builder.build().getEncoded();
        } catch (Exception e) {
            throw new RuntimeException("创建请求错误", e);
        }
    }

}
